import { useEffect, useRef, useState } from 'react';

const useResizeObserver = () => {
  const ref: any = useRef<any>(null);
  const [size, setSize] = useState<{ width: number; height: number }>({
    width: 0,
    height: 0,
  });

  useEffect(() => {
    const handleResize = (entries: ResizeObserverEntry[]) => {
      for (const entry of entries) {
        setSize({
          width: entry.contentRect.width,
          height: entry.contentRect.height,
        });
      }
    };

    const resizeObserver = new ResizeObserver(handleResize);
    const elm = ref.current;
    if (elm) {
      resizeObserver.observe(elm);
      setSize({
        width: elm.clientWidth,
        height: elm.clientHeight,
      });
    }

    return () => {
      if (elm) {
        resizeObserver.unobserve(elm);
      }
      resizeObserver.disconnect();
    };
  }, []);

  return [ref, size];
};

export default useResizeObserver;
